package com.huaruan.youdi.views.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ScrollView;

import com.huaruan.youdi.R;


/**
 * Created by yushilong on 2017/1/19.
 * 暂只支持从底部弹出，后期可以继续扩展
 */

public class BottomPushDialog extends Dialog {
    protected boolean isCancelable = true;
    protected View contentView;
    protected int contentViewResId = -1;
    protected OnClickListener onClickListener;
    protected int height;
    protected boolean isBgTranslate;//背景默认false是有个灰色的 true背景透明
    protected boolean isBgTranslateWhenDismiss = true;//dialog dismiss之前先去掉遮罩
    protected boolean isSwipeDownDismissEnable = false;//是否开启下滑关闭dialog功能，默认不开启,如果contentView是可滑动的view，需设置mScrollView为该可滑动的view
    protected ScrollView mScrollView;//可滑动的view

    public BottomPushDialog(Context context) {
        super(context, R.style.bottomPushDialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    public BottomPushDialog cancelable(boolean cancelable) {
        isCancelable = cancelable;
        return this;
    }

    public BottomPushDialog contentView(View contentView) {
        this.contentView = contentView;
        return this;
    }

    public BottomPushDialog contentViewResId(int contentViewResId) {
        this.contentViewResId = contentViewResId;
        contentView = View.inflate(getContext(), contentViewResId, null);
        return this;
    }

    public BottomPushDialog height(int height) {
        this.height = height;
        return this;
    }

    public BottomPushDialog setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
        return this;
    }

    public BottomPushDialog isBgTranslate(boolean isBgTranslate) {
        this.isBgTranslate = isBgTranslate;
        return this;
    }

    public BottomPushDialog isBgTranslateWhenDismiss(boolean bgTranslateWhenDismiss) {
        this.isBgTranslateWhenDismiss = bgTranslateWhenDismiss;
        return this;
    }

    public BottomPushDialog isSwipeDownDismissEnable(boolean swipeDownDismissEnable) {
        isSwipeDownDismissEnable = swipeDownDismissEnable;
        return this;
    }

    public BottomPushDialog scrollView(ScrollView scrollView) {
        mScrollView = scrollView;
        return this;
    }

    protected void init() {
        setCancelable(isCancelable);
        setCanceledOnTouchOutside(isCancelable);
        if (onClickListener != null)
            assignClickListenerRecursively(contentView);
        ViewGroup parent = (ViewGroup) View.inflate(getContext(), R.layout.base_dialog, null);
        if (contentView.getBackground() == null)
            contentView.setBackgroundColor(Color.WHITE);
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        parent.findViewById(R.id.mask).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : height);
        layoutParams.gravity = Gravity.BOTTOM;
        parent.addView(contentView, layoutParams);
        getWindow().setGravity(Gravity.BOTTOM);
        setContentView(parent);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (isSwipeDownDismissEnable) {
            final GestureDetector mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                    if (e1 != null && e2 != null) {
                        if (mScrollView != null) {
                            if ((e2.getRawY() - e1.getRawY()) > 300 && mScrollView.getScrollY() <= 0) {
                                dismiss();
                                return true;
                            }
                        } else {
                            if ((e2.getRawY() - e1.getRawY()) > 300) {
                                dismiss();
                                return true;
                            }
                        }

                    }
                    return super.onFling(e1, e2, velocityX, velocityY);
                }
            });
            contentView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return mGestureDetector.onTouchEvent(event);
                }
            });
            if (mScrollView != null)
                mScrollView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        return mGestureDetector.onTouchEvent(event);
                    }
                });
        }
    }

    @Override
    public void show() {
        super.show();
        if (!isBgTranslate)
            contentView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    findViewById(R.id.mask).animate().alpha(0.3f).setDuration(300).start();
                }
            }, 300);
    }

    @Override
    public void dismiss() {
        if (isBgTranslateWhenDismiss)
            findViewById(R.id.mask).setAlpha(0);
        contentView.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    BottomPushDialog.super.dismiss();
                } catch (Exception e) {

                }
            }
        }, 100);
    }

    private void assignClickListenerRecursively(View parent) {
        if (parent == null) {
            return;
        }
        if (parent instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) parent;
            int childCount = viewGroup.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View child = viewGroup.getChildAt(i);
                assignClickListenerRecursively(child);
            }
        }
        setClickListener(parent);
    }

    private void setClickListener(final View view) {
        if (view.getId() == -1) {
            return;
        }
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onClickListener == null) {
                    return;
                }
                onClickListener.onClick(BottomPushDialog.this, view);
            }
        });
    }

    public interface OnClickListener {
        void onClick(BottomPushDialog BottomPushDialog, View view);
    }

    public View contentView() {
        return contentView;
    }
}
